<template>
  <div class="the-list">

    <div class="panel-table">
      <div class="table-head">
        <span>数据列表</span>
        <div v-if="hasPermission(['operation:searchWord'])">
          <el-button type="primary" @click="sortFn.openPanel">排序</el-button>
          <el-button type="primary" @click="addEditFn.openPanel('add')">添加</el-button>
        </div>
      </div>
      <el-table :data="tableData.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>

        <!-- <el-table-column prop="id" label="ID" /> -->

        <el-table-column prop="sort" label="排序值" width="80px"/>
        <el-table-column prop="hotWordsName" label="推荐词" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="最后修改时间" />
        <el-table-column prop="status" label="当前状态">
          <template #default="{row}">
            <span :style="{color:['#D9001B','#70B603'][row.status]}">{{getItemFromArray(tagList.status,row.status) || "--"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="operationName" label="创建人" />
        <el-table-column prop="searchNum" label="使用次数" />

        <el-table-column fixed="right" label="操作" width="260px" align="center">
          <template #default="{row}">
            <el-button size="small" type="primary" plain @click="detailFn.openPanel(row)">详情</el-button>
            <template v-if="hasPermission(['operation:searchWord'])">
              <el-button size="small" type="primary" plain @click="addEditFn.openPanel('edit',row)">编辑</el-button>
              <el-button size="small" plain :type="row.status===0?'success':'warning'" @click="stateFn.sureUpdate(row)">{{row.status===0?'启用':'停用'}}</el-button>
              <el-button size="small" plain type="danger" @click="delFn.sureDelete(row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <pagination :total="tableData.total" v-model:page="tableData.query.page" v-model:limit="tableData.query.pageSize" @pagination="tableFn.getTableList" />
      </div>

    </div>

    <el-dialog v-model="detailData.showPanel" width="50%">
      <template #title>
        <div style="text-align:left;">搜索词详情</div>
      </template>
      <div class="detail-body">
        <el-form :model="detailData.detail" class="demo-form-inline" label-width="120px">
          <el-form-item label="搜索词">{{detailData.detail.hotWordsName}}</el-form-item>
          <el-form-item label="创建时间">{{detailData.detail.createdAt}}</el-form-item>
          <el-form-item label="最近修改时间">{{detailData.detail.updatedAt}}</el-form-item>
          <el-form-item label="当前状态">
            <span v-if="detailData.detail.status===0" style="color:#D9001B;">停用</span>
            <span v-else style="color:#70B603;">启用</span></el-form-item>
          <el-form-item label="创建人">{{detailData.detail.operationName}}</el-form-item>
          <el-form-item label="作品使用次数">{{detailData.detail.usedNum}}</el-form-item>
        </el-form>
      </div>
      <!-- <template #footer>
      <span class="dialog-footer">
        <el-button plain type="warning">停用</el-button>
        <el-button plain type="primary" @click="detailFn.closeDetailPanel();openAddOrEditPanel('edit',editOPT.data)">编辑</el-button>
        <el-button plain type="danger" @click="closeAddOrEditPanel">删除</el-button>
      </span>
    </template> -->
    </el-dialog>

    <el-dialog v-model="addEditData.showPanel" width="50%" @closed="addEditFn.closedPanel">
      <template #title>
        <div style="text-align:left;">添加/编辑搜索词</div>
      </template>
      <div class="detail-body">
        <el-form :model="addEditData.post" class="demo-form-inline" label-width="120px">
          <template v-if="addEditData.isEdit">
            <el-form-item label="ID">{{addEditData.post.id}}</el-form-item>
          </template>
          <el-form-item label="搜索词">
            <el-input v-model="addEditData.post.hotWordsName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button plain @click="addEditFn.closePanel">取消</el-button>
          <el-button plain type="primary" @click="addEditFn.submitData">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="sortData.showPanel" width="70%">
      <template #title>
        <div style="text-align:left;">搜索词排序</div>
      </template>
      <div class="sort-body">
        <template v-for="(item) in sortData.list" :key="item.id">
          <div class="item">
            <p class="item-name">{{item.hotWordsName}}</p>
            <el-input-number v-model="item.sort" :min="0" :max="100000" controls-position="right" @change="sortFn.updateItem(item.id,$event)" />
          </div>
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button plain @click="sortFn.closePanel">取消</el-button>
          <el-button plain type="primary" @click="sortFn.submitData">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>


<script>
import { reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getHotWordsTagsList, addHotWordsTag, editHotWordsTag, editHotWordsTagStatus, deleteHotWordsTag, editHotWordsTagSort }  from "@/api/operation.js";
import Pagination from "@/components/Pagination";
import { tagList,getItemFromArray }  from "@/utils/tool.js";

export default {
  name: "topicTags",
  components:{
    Pagination,
  },
  setup() {
    // 默认数据备份，以便重置或恢复
    const { $data: tableData, $fn: tableFn } = tableModule();
    const { $data: detailData, $fn: detailFn } = detailModule();
    const { $data: addEditData, $fn: addEditFn } = addOrEditModule(tableFn);
    const { $data: delData, $fn: delFn } = deleteModule(tableFn);
    const { $data: stateData, $fn: stateFn } = stateModule(tableFn);
    const { $data: sortData, $fn: sortFn } = sortModule(tableData,tableFn);

    return {
      tableData,
      tableFn,
      detailData,
      detailFn,
      addEditData,
      addEditFn,
      delData,
      delFn,
      stateData,
      stateFn,
      sortData,
      sortFn,
      tagList,getItemFromArray,
    };
  },
};

// 表格功能模块，包括搜索，分页等
function tableModule() {
  const backup = {
    query: {
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    list: [],
    total: 0,
  });
  const $fn = {
    getTableList() {
      getHotWordsTagsList($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableList();
    },
    onSubmit() {
      $fn.getTableList();
    },
  };

  $fn.getTableList();

  return {
    $data,
    $fn,
  };
}

// 详情
function detailModule() {
  const $data = reactive({
    showPanel: false,
    detail: {}, //详情数据
  });
  const $fn = {
    openPanel(row) {
      $data.showPanel = true;
      $data.detail = { ...row };
    },
    closePanel() {
      $data.showPanel = false;
    },
  };
  return {
    $data,
    $fn,
  };
}

// 新增、编辑
function addOrEditModule(tableFn) {
  const $data = reactive({
    showPanel: false,
    isEdit: false,
    post: {
      id: "",
      hotWordsName: "",
    }, //提交的数据
  });
  const $fn = {
    openPanel(operate, row) {
      if (operate === "add") {
        $data.isEdit = false;
        $data.post.hotWordsName = "";
      } else if (operate === "edit") {
        $data.isEdit = true;
        $data.post.id = row.id;
        $data.post.hotWordsName = row.hotWordsName;
      }
      $data.showPanel = true;
    },
    closePanel() {
      $data.showPanel = false;
    },
    closedPanel(){
      $data.post={
        id: "",
        hotWordsName: "",
      }
    },
    submitData() {
      console.log("req data:", $data.post);
      let {id,hotWordsName} = $data.post;
      // 数据验证
      if(!hotWordsName){
        ElMessage.danger("请填写推荐词名称！");
        return;
      }
      if($data.isEdit){
        let req = {id,hotWordsName};
        editHotWordsTag(req).then(res=>{
          if(res.code===0){
            ElMessage.success("修改成功！");
            tableFn.getTableList();
            $fn.closePanel();
          }
        })
      }else{
        let req = {hotWordsName};
        addHotWordsTag(req).then(res=>{
          if(res.code===0){
            ElMessage.success("添加成功！");
            tableFn.getTableList();
            $fn.closePanel();
          }
        })
      }
    },
  };
  return {
    $data,
    $fn,
  };
}

// 删除
function deleteModule(tableFn) {
  const $fn = {
    sureDelete(row) {
      ElMessageBox.confirm("是否确认删除该话题？", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $fn.deleteItem(row);
      }).catch(() => {});
    },
    deleteItem(row) {
      // 发起删除
      console.log("发起删除");
      deleteHotWordsTag(row.id).then((res)=>{
        if(res.code===0){
          ElMessage.success("删除成功！");
          tableFn.getTableList();
        }
      })
    },
  };
  return {
    $fn,
  };
}

// 修改状态
function stateModule(tableFn) {
  const $fn = {
    sureUpdate(row) {
      let text = row.status ? "停用" : "启用";
      ElMessageBox.confirm(`是否确认${text}该话题？`, `确认${text}`, {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        $fn.updateItem(row);
      }).catch(() => {});
    },
    updateItem(row) {
      let text = row.status ? "停用" : "启用";
      editHotWordsTagStatus({id:row.id,status:row.status===0?1:0}).then((res)=>{
        if(res.code===0){
          ElMessage.success(`${text}成功！`);
          tableFn.getTableList();
        }
      })
    },
  };
  return {
    $fn,
  };
}

// 排序
function sortModule(tableData,tableFn) {
  const data = {
    listMap: new Map(),
  };
  const $data = reactive({
    list: [],
    showPanel: false,
    postMap: new Map(), //提交的数据
  });
  const $fn = {
    openPanel() {
      $data.showPanel = true;
      $fn.getSortList();
    },
    closePanel() {
      $data.showPanel = false;
      data.listMap.clear();
    },
    // 获取全部启用的标签
    getSortList() {
      getHotWordsTagsList({ ...tableData.query, page: 1, pageSize: tableData.total, status: 1 }).then(
        (res) => {
          if (res.code === 0) {
            // 转为map数据，以便快捷查询
            for (let prop of res.data.items || []) {
              data.listMap.set(prop.id, { ...prop });
            }
            $data.list = res.data.items || [];
          }
        }
      );
    },
    // 修改了哪一项
    updateItem(id, sort) {
      if (data.listMap.get(id).sort !== sort) {//修改了
        $data.postMap.set(id, { id, sort });
      } else {//未改动
        $data.postMap.delete(id);
      }
    },
    submitData() {
      let req = [...$data.postMap.values()];
      editHotWordsTagSort(req).then(res=>{
        if(res.code===0){
          ElMessage.success("修改排序成功！");
          $fn.closePanel();
          tableFn.getTableList();
        }
      })
    },
  };
  return {
    $data,
    $fn,
  };
}
</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
.the-list {
  height: 100%;
}
.el-form-item {
  margin-bottom: 8px;
}

.sort-body {
  .item {
    padding: 8px;
    width: 33.33%;
    box-sizing: border-box;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    p {
      display: inline-block;
    }
    .item-name {
      padding-right: 8px;
    }
    &:nth-child(odd) {
      background-color: rgb(248, 248, 248);
    }
    // &:nth-child(even){
    //   background-color: rgb(255, 237, 237);
    // }
  }
}
</style>